package net.xdclass.rbac_shiro.config;

import com.alibaba.druid.util.StringUtils;
import net.xdclass.rbac_shiro.domain.Permission;
import net.xdclass.rbac_shiro.domain.Role;
import net.xdclass.rbac_shiro.domain.User;
import net.xdclass.rbac_shiro.service.UserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;

/**
 * @program: rbac_shiro
 * @description: 自定义Realm
 * @author: rZ
 * @create: 2020-01-10 10:20
 **/
public class CustomRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;

    /**
     * 进行权限校验的时候会调用
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        User newUser = (User)principalCollection.getPrimaryPrincipal();
        User user = userService.findAllUserInfoByUserName(newUser.getUsername());
        //角色列表
        List<String> stringRoleList = new ArrayList<>();
        //权限列表
        List<String> stringPermissionList = new ArrayList<>();
        List<Role> roleList = user.getRoleList();
        for (Role role : roleList) {
            stringRoleList.add(role.getName());
            List<Permission> permissionList = role.getPermissionList();
            for (Permission permission : permissionList) {
                if (permission != null) {
                    stringPermissionList.add(permission.getName());
                }
            }
        }
        //创建用户对象
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        simpleAuthorizationInfo.addRoles(stringRoleList);
        simpleAuthorizationInfo.addStringPermissions(stringPermissionList);
        return simpleAuthorizationInfo;
    }

    /**
     * 用户认证，登陆时调用
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {

        //从token中获取用户信息，token代表用户输入的信息
        String username = (String)authenticationToken.getPrincipal();
        User user = userService.findAllUserInfoByUserName(username);
        String pwd = user.getPassword();
        if (StringUtils.isEmpty(pwd)){
            return null;
        }
        //创建用户对象
        SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(user,pwd,this.getClass().getName());
        return simpleAuthenticationInfo;
    }
}
